package com.yc;

import com.yc.bean.Resfood;
import com.yc.commons.DBHelper;
import com.yc.model.PageBean;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

/**
 * @author zwei
 * @create 2024-06-16 16:18
 */
public class ResfoodBiz {
    public PageBean findByPage(PageBean pageBean) throws InvocationTargetException, InstantiationException, IllegalAccessException {
        List<Resfood> dataset=this.findByPage(pageBean.getPageno(),pageBean.getPagesize(),pageBean.getSortby(),pageBean.getSort());
        long total=this.countAll();

        pageBean.setTotal(total);
        pageBean.setDataset(dataset);
        //其他分页数据
        //计算总页数
        long totalPages=total%pageBean.getPagesize()==0?total/pageBean.getPagesize():total/pageBean.getPagesize()+1;
        pageBean.setTotalpages((int) totalPages);
        //上一页页号的计算
        if (pageBean.getPageno()<=1){
            pageBean.setPre(1);
        }else {
            pageBean.setPre(pageBean.getPageno()-1);
        }
        //下一页的页号
        if (pageBean.getPageno()==totalPages){
            pageBean.setNext((int) totalPages);
        }else {
            pageBean.setNext(pageBean.getPageno()+1);
        }
        return pageBean;
    }

    /**
     * 查询resfood的记录条数
     * @return
     */
    private long countAll(){
        String sql="select count(fid) from resfood";
        DBHelper dbHelper=new DBHelper();
        List<Map<String,Object>>list=dbHelper.select(sql);
        Map<String,Object>map=list.get(0);
        long l= (long) map.get("count(fid)");
        return l;
    }
    private List<Resfood>findByPage(int pageno,int pagesize,String sortby,String sort) throws InvocationTargetException, InstantiationException, IllegalAccessException {
        String sql = "SELECT * FROM resfood ORDER BY "+ sortby + " " + sort + " LIMIT ?, ?";

        DBHelper dbHelper = new DBHelper();
        int start = (pageno - 1) * pagesize;
        List<Resfood> list = dbHelper.select(Resfood.class, sql, start, pagesize);

        return list;
    }
}
